/*
 * Copyright (C) 2011 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_Allocating.java
 *
 * Created on 26/08/2011, 23:40:51
 */
package kuasar.plugin.deployer.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import javax.swing.JPanel;
import javax.swing.Timer;
import kuasar.plugin.Intercom.GUI;
import kuasar.plugin.deployer.gui.actions.CompareArrays;
import kuasar.plugin.deployer.gui.actions.dialogs.pn_AllocateErr;
import kuasar.plugin.deployer.gui.actions.th_AllocateVMs;
import kuasar.plugin.deployer.gui.classmod.I_Panels;
import org.jdom.Element;

/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_Allocating extends kuasar.plugin.classMod.AbstractPanel implements I_Panels {
    
    private boolean ramfirst;
    private Element vms;
    private Element servers;
    private JPanel previous;
    protected JPanel first;
    private th_AllocateVMs scanner = null;
    int currentFrame =0;
    private Timer imageAllocating = new Timer (50, new ActionListener ()
        {
        @Override
            public void actionPerformed(ActionEvent e)
            {
                currentFrame++;
                javax.swing.ImageIcon icon;
                try{
                    icon = new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/animation/allocating/allocating" + currentFrame + ".png"));
                }catch(NullPointerException ex){
                    currentFrame=1;
                    icon =  new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/animation/allocating/allocating" + currentFrame + ".png"));
                }
                lbl_Image.setIcon(icon);
             }
        }); 
    /*
     * vmdata HashMap[>tring, String[]]:
     *          [0] : NICE NAME
     *          [1] : ENGINECODE
     *          [2] : TOTAL IMAGE LENGTH (LONG)
     *          [3] : VM RAM (LONG)
     *          [4] : SAFE RAM (BOOLEAN)
     */
    private HashMap<String, TreeSet<String[]>> vmdata = new HashMap<String, TreeSet<String[]>>();
    
    /** Creates new form pn_Awarding */
    public pn_Allocating(Element vms, Element servers, boolean ramfirst, JPanel first, JPanel parent) {
        this.first = first;
        this.previous = parent;
        this.ramfirst = ramfirst;
        this.vms = vms;
        this.servers = servers;
        initComponents();
        imageAllocating.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pn_Upper = new javax.swing.JPanel();
        lbl_Image = new javax.swing.JLabel();
        pn_Right = new javax.swing.JPanel();
        pn_Left = new javax.swing.JPanel();
        pn_Lower = new javax.swing.JPanel();
        btn_Next = new javax.swing.JButton();
        lbl_Info = new javax.swing.JLabel();
        btn_Back = new javax.swing.JButton();
        lbl_Title = new javax.swing.JLabel();

        setOpaque(false);

        pn_Upper.setOpaque(false);

        javax.swing.GroupLayout pn_UpperLayout = new javax.swing.GroupLayout(pn_Upper);
        pn_Upper.setLayout(pn_UpperLayout);
        pn_UpperLayout.setHorizontalGroup(
            pn_UpperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 633, Short.MAX_VALUE)
        );
        pn_UpperLayout.setVerticalGroup(
            pn_UpperLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 48, Short.MAX_VALUE)
        );

        lbl_Image.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_Image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/animation/allocating/allocating1.png"))); // NOI18N

        pn_Right.setOpaque(false);

        javax.swing.GroupLayout pn_RightLayout = new javax.swing.GroupLayout(pn_Right);
        pn_Right.setLayout(pn_RightLayout);
        pn_RightLayout.setHorizontalGroup(
            pn_RightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        pn_RightLayout.setVerticalGroup(
            pn_RightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 219, Short.MAX_VALUE)
        );

        pn_Left.setOpaque(false);

        javax.swing.GroupLayout pn_LeftLayout = new javax.swing.GroupLayout(pn_Left);
        pn_Left.setLayout(pn_LeftLayout);
        pn_LeftLayout.setHorizontalGroup(
            pn_LeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        pn_LeftLayout.setVerticalGroup(
            pn_LeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 219, Short.MAX_VALUE)
        );

        pn_Lower.setOpaque(false);

        btn_Next.setBackground(new java.awt.Color(0, 0, 0));
        btn_Next.setForeground(new java.awt.Color(204, 204, 204));
        btn_Next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/next22.png"))); // NOI18N
        btn_Next.setText("Next");
        btn_Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_NextActionPerformed(evt);
            }
        });

        lbl_Info.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Info.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        btn_Back.setBackground(new java.awt.Color(0, 0, 0));
        btn_Back.setForeground(new java.awt.Color(204, 204, 204));
        btn_Back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/previous22.png"))); // NOI18N
        btn_Back.setText("Back");
        btn_Back.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Back.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_BackActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pn_LowerLayout = new javax.swing.GroupLayout(pn_Lower);
        pn_Lower.setLayout(pn_LowerLayout);
        pn_LowerLayout.setHorizontalGroup(
            pn_LowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pn_LowerLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pn_LowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pn_LowerLayout.createSequentialGroup()
                        .addComponent(btn_Back)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_Next))
                    .addComponent(lbl_Info, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE))
                .addContainerGap())
        );
        pn_LowerLayout.setVerticalGroup(
            pn_LowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pn_LowerLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_Info)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(pn_LowerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_Next)
                    .addComponent(btn_Back))
                .addContainerGap())
        );

        btn_Next.setVisible(false);

        lbl_Title.setFont(new java.awt.Font("Dialog", 1, 28));
        lbl_Title.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Title.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/calc48.png"))); // NOI18N
        lbl_Title.setText("Allocating...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pn_Left, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lbl_Image, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Right, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(pn_Lower, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_Title, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(pn_Upper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(lbl_Title, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Upper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(pn_Left, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbl_Image, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                    .addComponent(pn_Right, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pn_Lower, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void btn_BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_BackActionPerformed
    goPrevious();
}//GEN-LAST:event_btn_BackActionPerformed

private void btn_NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_NextActionPerformed
    goNext();
}//GEN-LAST:event_btn_NextActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Back;
    private javax.swing.JButton btn_Next;
    private javax.swing.JLabel lbl_Image;
    private javax.swing.JLabel lbl_Info;
    private javax.swing.JLabel lbl_Title;
    private javax.swing.JPanel pn_Left;
    private javax.swing.JPanel pn_Lower;
    private javax.swing.JPanel pn_Right;
    private javax.swing.JPanel pn_Upper;
    // End of variables declaration//GEN-END:variables
    
    public void startScanning(){
        loadVMRequirements(vms, "/","/");
        ArrayList<String[]> addresses = loadServerInfo();
        scanner = new th_AllocateVMs(addresses, vmdata, ramfirst , this);
        scanner.start();
    }
    public void finished(ArrayList<String[]> allocated){
        imageAllocating.stop();
       for(String[] data : allocated){
           String vm = data[0];
           String server = data[1];
           String port = data[2];
           String[] path = vm.split("/");
           Element element = vms;
           for(String item : path){
               if(!item.isEmpty())
                   element = element.getChild(item);
           }
           element.setAttribute("server", server);
           element.setAttribute("server.port", port);
       }
       lbl_Image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/deployer/icons/ok128.png")));
       btn_Next.setVisible(true);
       goNext();
    }

    private ArrayList<String[]> loadServerInfo() {
        ArrayList<String[]> addresses = new ArrayList<String[]>();
        if(servers.getAttributeValue("type") == null){
            recursiveScan(servers,addresses);
        }else if(servers.getAttributeValue("type").isEmpty()){
            recursiveScan(servers,addresses);
        }else if(servers.getAttributeValue("type").equals("server")){
            addresses.add(new String[]{servers.getAttributeValue("address"),servers.getAttributeValue("port")});
        }
        return addresses;
    }

    private void recursiveScan(Element servers, ArrayList<String[]> addresses) {
        List<Element> children = servers.getChildren();
        for(int i = 0; i<children.size(); i++){
            Element child = children.get(i);
            if(child.getAttributeValue("type").isEmpty()){
                recursiveScan(child, addresses);
            }else if(child.getAttributeValue("type").equals("server")){
                addresses.add(new String[]{child.getAttributeValue("address"),child.getAttributeValue("port")});
            }
        }
    }

    private void loadVMRequirements(Element parent,String path, String name) {
        List<Element> children = parent.getChildren();
        for(Element child : children){
            if(child.getAttributeValue("type").equals("dir")){
                loadVMRequirements(child, path + child.getName()+"/", name + child.getAttributeValue("name") +"/");
            }else if(child.getAttributeValue("type").equals("vm")){
                TreeSet<String[]> vmInfo;
                if(vmdata.containsKey(child.getAttributeValue("hv"))){
                    vmInfo = vmdata.get(child.getAttributeValue("hv"));
                }else{
                    vmInfo = new TreeSet<String[]>(new CompareArrays(ramfirst));
                    
                }
                String[] data = new String[5];
                data[0] = path + child.getName();
                data[1] = name + child.getAttributeValue("name");
                data[2] = sumVMImg(child.getChild("dev"));
                data[3] = child.getAttributeValue("mem");
                data[4] = child.getAttributeValue("safe");
                vmInfo.add(data);
                
                vmdata.put(child.getAttributeValue("hv"), vmInfo);   
            }
        }
    }

    private String sumVMImg(Element child) {
        long total = 0;
        List<Element> modules = child.getChildren();
        for(Element module : modules){
            List<Element> devices = module.getChildren();
            for(Element device : devices){
                String img = device.getAttributeValue("file");
                if(img != null){
                    File file = new File(img);
                    total += file.length();
                }
            }
        }
        return Long.toString(total);
    }

    public void showErrors(ArrayList<String[]> errors) {
        GUI.loadPlugin(new pn_AllocateErr(errors,first));
        GUI.updateUI();
    }

    public void setInfo(String msg){
        lbl_Info.setText(msg);
    }
    
    @Override
    public void goNext() {
        GUI.loadPlugin(new pn_Allocated(vms,previous, first));
        GUI.updateUI();
    }

    @Override
    public void goPrevious() {
        if(scanner !=null)
            if(scanner.isAlive())
                scanner.cleanStop();
        GUI.loadPlugin(previous);
        GUI.updateUI();
    }

}
